<template>
    <div class="edu-page-warp">
        <div style="background:#fff;">
            <div class="base-sub-title">{{ studentCultureRel.major }}{{ $t("culturePlan.culturePlan") }}</div>
            <!--分类与课程统计-->
            <div style="width:100%;overflow:auto;font-size:12px;">
                <table class="personal">
                    <thead>
                        <tr>
                            <th
                                :colspan="tableDynamicColNum"
                                style="min-width:120px"
                            >{{ $t("culturePlan.courseCategory") }}</th>
                            <th style="width:50px">{{ $t("culturePlan.courseCode") }}</th>
                            <th style="min-width:60px">{{ $t("culturePlan.courseName") }}</th>
                            <th style="min-width:40px">{{ $t("culturePlan.studyScore") }}</th>
                            <th style="min-width:40px">{{ $t("culturePlan.studyTime") }}</th>
                            <th style="min-width:60px">{{ $t("course.term") }}</th>
                            <th style="min-width:125px">{{ $t("label.openClassCollege") }}</th>
                            <th style="min-width:60px">{{ $t("culturePlan.obligatory") }}</th>
                            <th style="min-width:60px">{{ $t("culturePlan.amongNumber") }}</th>
                            <th style="max-width:120px">{{ $t("culturePlan.remark") }}</th>
                            <th v-if="prev" style="min-width:60px">{{ $t("culturePlan.selectCourse") }}</th>
                            <th v-if="prev" style="min-width:40px">{{ $t("culturePlan.achievement") }}</th>
                            <th
                                v-if="prev"
                                style="min-width:80px"
                            >{{ $t("culturePlan.finishStatus") }}</th>
                            <th v-if="!prev" style="min-width:80px">{{ $t("message.operating") }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(c,_index) in courses" :key="_index">
                            <!--数据列-->
                            <template v-for="col in (c.label ? c.label.labelMap : [])">
                                <td
                                    v-if="col.rowspan!=0"
                                    :rowspan="col.rowspan"
                                    :colspan="col.colspan"
                                    :key="col.id"
                                >{{ col.name }}</td>
                            </template>
                            <td v-if="c.type=='row'" class="nowrap">
                                <div class="nowrap" style="width:80px">
                                    <el-tooltip
                                        :content="c.code"
                                        effect="light"
                                        placement="top-start"
                                        open-delay="200"
                                    >
                                        <span class="tooltip">{{ c.code }}</span>
                                    </el-tooltip>
                                </div>
                            </td>
                            <td v-if="c.type=='row'" class="nowrap" style="text-align:center;" width="150px">
                                <div class="nowrap" style="width:100%;max-width:150px;">
                                    <el-tooltip
                                        :content="language=='en'?c.nameEn:c.name"
                                        effect="light"
                                        placement="top-start"
                                        open-delay="200"
                                    >
                                        <a
                                            class="tooltip"
                                            @click="showCourseDetail(c)"
                                        >
                                            {{ language=='en'?c.nameEn:c.name }}
                                        </a>
                                    </el-tooltip>
                                </div>
                            </td>
                            <td v-if="c.type=='row'">
                                <span>
                                    {{ c.credits }}
                                </span>
                            </td>
                            <td v-if="c.type=='row'">
                                <span>
                                    {{ c.period }}
                                </span>
                            </td>
                            <td v-if="c.type=='row'">{{ getTermText(c.term) }}</td>
                            <td v-if="c.type=='row'">{{ c.collegeI18n }}</td>
                            <td v-if="c.type=='row'">{{ c.compulsory | yesOrNo(language) }}</td>
                            <!--分组信息-->
                            <td
                                v-if="c.type=='row' && c.colspan != 0"
                                :rowspan="c.colspan"
                                width="83px"
                            >{{ c.parentRemark }}</td>
                            <td v-if="c.type=='row'" width="120px">
                                <div class="nowrap" style="width:100%;max-width:120px;">
                                    <el-tooltip
                                        :content="language=='en'?c.remarksEn:c.remarks"
                                        effect="light"
                                        placement="top-start"
                                        open-delay="200"
                                    >
                                        <span class="tooltip">{{ language=='en'?c.remarksEn:c.remarks }}</span>
                                    </el-tooltip>
                                </div>
                            </td>
                            <td v-if="c.type=='row'&&prev">
                                {{ c.selCourse=="1"?$t('culturePlan.graduatePlan.textTrue'):$t('culturePlan.graduatePlan.textFalse') }}
                            </td>
                            <td v-if="c.type=='row'&&prev">{{ c.score }}</td>
                            <td
                                v-if="c.type=='blank' && (c.labelId == 1581 || c.labelId == 1070)"

                                colspan="12"
                            />
                            <td
                                v-if="c.type=='blank' && (c.labelId ==1039 || c.labelId ==1071|| c.labelId ==1550|| c.labelId ==1582 )"
                                colspan="12"
                            />
                            <!--空课程结束-->
                            <td v-if="prev">
                                <template v-if="c.isScorePass == 1">
                                    {{ $t('culturePlan.graduatePlan.textTrue') }}
                                </template>
                                <template v-if="c.isScorePass == 0 || c.isScorePass == null">
                                    {{ $t('culturePlan.graduatePlan.textFalse') }}
                                </template>
                            </td>
                            <td v-if="c.type=='row'&&!prev" style="text-align:left">
                                <div v-if="c.labelId != 999999" style="margin-left:10px;">
                                    <!-- <el-button
                                        type="text"
                                        @click="moveCourse(c)"
                                        v-if="'2'===c.label.labelType&&c.isScorePass&&c.selCourse"
                                        size="mini"
                                    >{{$t("culturePlan.move")}}</el-button>-->
                                    <!-- <el-button
                                        type="text"
                                        @click="showDeleteDialog(c)"
                                        size="mini"
                                    >{{$t("culturePlan.cancelCourse")}}</el-button>
                                    <el-button
                                        type="text"
                                        @click="showAppendDialog(c)"
                                        v-if="c.labelId!=999999 && c.isLast"
                                        size="mini"
                                    >{{$t("culturePlan.add")}}</el-button>-->
                                    <template v-if="statusPlan == -1">
                                        <div v-if="c.courseTag*1==1">
                                            <el-button
                                                :class="c.chosen*1==1?'selected-course':''"
                                                type="text"
                                                size="mini"
                                                @click="getSmallCourses(c)"
                                            >{{ !c.chosen*1?$t('culturePlan.graduatePlan.selection'):$t('culturePlan.graduatePlan.deselection') }}</el-button>
                                        </div>
                                        <div v-else>
                                            <el-button
                                                v-if="c.selected"
                                                :class="'selected-course'"
                                                type="text"
                                                size="mini"
                                                @click="resetSelected(c)"
                                            >{{ $t('culturePlan.graduatePlan.deselection') }}</el-button>
                                            <el-button
                                                v-else
                                                type="text"
                                                size="mini"
                                                @click="resetSelected(c)"
                                            >{{ $t('culturePlan.graduatePlan.selection') }}</el-button>
                                            <el-button
                                                v-if="c.isEditType&&c.selected"
                                                type="text"
                                                size="mini"
                                                @click="removeCourse(c,statusPlan)"
                                            >{{ $t('culturePlan.graduatePlan.reviseCourseType') }}</el-button>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <div v-if="c.courseTag*1==1">
                                            <el-button
                                                v-if="c.chosen*1==1"
                                                :class="c.chosen*1!=1?'selected-course':''"
                                                type="text"
                                                size="mini"
                                                @click="getSmallCourses(c)"
                                            >{{ !c.chosen*1?$t('culturePlan.graduatePlan.selection'):$t('culturePlan.graduatePlan.deselection') }}</el-button>
                                            <el-button
                                                v-else
                                                :class="c.chosen*1!=1?'selected-course':''"
                                                type="text"
                                                size="mini"
                                                @click="getSmallCourses(c)"
                                            >{{ !c.chosen*1?$t('culturePlan.graduatePlan.selection'):$t('culturePlan.graduatePlan.deselection') }}</el-button>
                                        </div>
                                        <div v-else>
                                            <el-button
                                                v-if="c.selected"
                                                :class="'selected-course'"
                                                type="text"
                                                size="mini"
                                                @click="resetSelected(c)"
                                            >{{ $t('culturePlan.graduatePlan.deselection') }}</el-button>
                                            <el-button
                                                v-else
                                                type="text"
                                                size="mini"
                                                @click="resetSelected(c)"
                                            >{{ $t('culturePlan.graduatePlan.selection') }}</el-button>
                                            <el-button
                                                v-if="c.isEditType&&c.selected"
                                                type="text"
                                                size="mini"
                                                @click="removeCourse(c,statusPlan)"
                                            >{{ $t('culturePlan.graduatePlan.reviseCourseType') }}</el-button>
                                        </div>
                                    </template>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td :colspan="tableDynamicColNum+2">{{ $t("culturePlan.total") }}</td>
                            <td>{{ totalScore }}</td>
                            <td>{{ totalTime }}</td>
                            <td :colspan="tableStaticColNum-2"/>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div v-if="!prev" style="float:right;margin:10px 0">
            <el-button @click="back">{{ $t("message.cancel") }}</el-button>
            <el-button type="primary" @click="saveCourse">{{ $t("message.save") }}</el-button>
            <el-button type="primary" @click="submitCourse">{{ $t("message.submit") }}</el-button>
        </div>
        <!-- 根据大课选小课 -->
        <el-dialog
            :title="selectedCoursesName"
            :visible.sync="showSelectDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="70%"
        >
            <template>
                <el-table
                    ref="multipleTable"
                    :data="allSmallCourses"
                    border
                    size="mini"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column type="selection" width="35"/>
                    <el-table-column :label="$t('culturePlan.courseCode')" prop="courseCode"/>
                    <el-table-column :label="$t('culturePlan.courseName')" prop="name"/>
                </el-table>
                <div style="text-align:right;">
                    <el-button type="primary" @click="getCoursesParams()">{{ $t("message.confirm") }}</el-button>
                    <el-button @click="cancelSmallCourses">{{ $t("message.cancel") }}</el-button>
                </div>
            </template>
        </el-dialog>
        <!--添加课程对话框-->
        <el-dialog
            v-if="!prev"
            :title="$t('culturePlan.addCourse')"
            :visible.sync="showAddDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="70%"
        >
            <div>
                <div class="edu-page-title">{{ $t("message.filterCondition") }}</div>
                <el-form label-position="left" label-width="70px">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item :label="$t('culturePlan.courseCategory')+'：'">
                                <el-select v-model="queryForm.nature">
                                    <el-option
                                        v-for="item in options.nature"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item :label="$t('label.openClassCollege')">
                                <el-select v-model="queryForm.college">
                                    <el-option
                                        v-for="item in options.college"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item :label="$t('course.term')">
                                <el-select v-model="queryForm.term">
                                    <el-option
                                        v-for="item in options.kkxq"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" style="text-align:right">
                            <el-button @click="resetAddCourse">{{ $t("message.reset") }}</el-button>
                            <el-button
                                type="primary"
                                @click="filterAddCourse"
                            >{{ $t("message.filter") }}</el-button>
                        </el-col>
                    </el-row>
                </el-form>
                <div class="edu-page-title">
                    <el-row>
                        <el-col :span="8">{{ $t("culturePlan.courseList") }}</el-col>
                        <el-col :span="16" style="text-align:right">
                            <el-input
                                v-model="searchCourse"
                                :placeholder="$t('culturePlan.courseName')+'、'+$t('culturePlan.courseCode')"
                                style="width:240px"
                                @keyup.enter.native="searchAddCourse"
                            >
                                <i
                                    slot="suffix"
                                    class="el-icon-search"
                                    style="margin-top:10px;cursor:pointer"
                                    @click="searchAddCourse"
                                />
                            </el-input>
                            <el-button @click="clearAddCourse">{{ $t("culturePlan.clearChecked") }}</el-button>
                        </el-col>
                    </el-row>
                </div>
                <el-row :gutter="20">
                    <el-col>
                        <table class="personal" style="margin:10px 0">
                            <thead>
                                <th style="width:130px">{{ $t('culturePlan.courseCode') }}</th>
                                <th>{{ $t('culturePlan.courseName') }}</th>
                                <th>{{ $t('culturePlan.studyScore') }}</th>
                                <th>{{ $t('culturePlan.studyTime') }}</th>
                                <th>{{ $t('culturePlan.semester') }}</th>
                                <th>{{ $t('culturePlan.obligatory') }}</th>
                                <th>{{ $t('culturePlan.remark') }}</th>
                            </thead>
                            <tbody>
                                <tr v-for="(c,_index) in filterLabelCourses" :key="_index">
                                    <td style="text-align:left">
                                        <div style="margin-left:10px">
                                            <el-checkbox
                                                v-if="c.disabled"
                                                v-model="c.checked"
                                                disabled
                                            />
                                            <el-checkbox v-if="!c.disabled" v-model="c.checked"/>
                                            <span style="margin-left:10px">{{ c.code }}</span>
                                        </div>
                                    </td>
                                    <td>{{ c.coursesName }}</td>
                                    <td>{{ c.credits }}</td>
                                    <td>{{ c.period }}</td>
                                    <td>{{ getTermText(c.term) }}</td>
                                    <td>{{ c.compulsory | yesOrNo }}</td>
                                    <td v-if="!c.courseGroupId">{{ c.parentRemark }}</td>
                                    <td
                                        v-if="c.courseGroupId&&c.rowspan"
                                        :rowspan="c.rowspan"
                                    >{{ c.parentRemark }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </el-col>
                </el-row>
                <el-row v-if="rawLabelCourse.length>0">
                    <el-col>
                        <div style="text-align:right">
                            <el-button @click="cancelCourseSave">{{ $t("message.cancel") }}</el-button>
                            <el-button type="primary" @click="addCourseSave">{{ $t("message.save") }}</el-button>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>
        <!--验证信息汇总-->
        <el-dialog
            :title="$t('culturePlan.tipMessage')"
            :visible.sync="showRulesDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="50%"
        >
            <div style="overflow:auto">
                <div style="color:red;line-height:30px">*{{ $t('culturePlan.condition') }}：</div>
                <div v-for="(c,index) in rules" :key="index" style="line-height:30px">
                    <div
                        v-if="c.type=='score'"
                    >{{ c.name }}，{{ $t('culturePlan.needScore') }}：{{ c.credit }}，{{ $t('culturePlan.currentScore') }}：{{ c.score }}</div>
                    <div
                        v-if="c.type=='num'"
                    >{{ c.name }}，{{ $t('culturePlan.maxCourseNum') }}：{{ c.maxNum }}，{{ $t('culturePlan.minCourseNum') }}：{{ c.minNum }}，{{ $t('culturePlan.currentCourseNum') }}：{{ c.num }}</div>
                    <!-- <div v-if="c.type=='foreign'">
                        <div>{{$t('culturePlan.firstForeignMinCourse')}}:{{c.rulesCode}}</div>
                        <div>{{$t('culturePlan.courseLimit')}}:{{c.maxNumber}}</div>
                        <div>{{$t('culturePlan.selectedMinCourse')}}:{{c.findCode}}</div>
                    </div> -->
                    <div v-if="c.type=='foreign'">
                        <div>{{ $t('culturePlan.graduatePlan.firstforginLanguage') }}</div>
                    </div>
                    <div v-if="c.type=='groupNum'">
                        <div>
                            {{ $t('culturePlan.courseCategory') }} {{ c.label }}：{{ c.groupRemark }} {{ c.parentRemark }}，
                            {{ $t('culturePlan.graduatePlan.minimumCourses') }}：
                            <b
                                style="color:red"
                            >{{ c.maxNum }}</b>，
                            {{ $t('culturePlan.graduatePlan.numberSelectedCourses') }}：
                            <b style="color:#009900">{{ c.actNum }}</b>
                        </div>
                    </div>
                    <div v-if="c.type=='groupNums'">
                        <div>
                            {{ $t('culturePlan.courseCategory') }} {{ c.label }}：{{ c.groupRemark }} {{ c.parentRemark }}，
                            {{ $t('culturePlan.graduatePlan.requiredCourses') }}：
                            <b
                                style="color:red"
                            >{{ c.maxNum }}</b>，
                            {{ $t('culturePlan.graduatePlan.numberSelectedCourses') }}：
                            <b style="color:#009900">{{ c.actNum }}</b>
                        </div>
                    </div>
                    <div v-if="c.type=='groupCredits'">
                        <div>
                            {{ $t('culturePlan.courseCategory') }} {{ c.label }}：{{ c.groupRemark }} {{ c.parentRemark }}，
                            {{ $t('culturePlan.graduatePlan.requiredScore') }}
                            <b
                                style="color:red"
                            >{{ c.expression }} {{ c.minNum }}</b>，
                            {{ $t('culturePlan.graduatePlan.selectedCredits') }}：
                            <b style="color:#009900">{{ c.actNum }}</b>
                        </div>
                    </div>
                    <div v-if="c.type=='bigGroup'">
                        <div>
                            {{ c.label }} {{ c.groupRemark }}，{{ $t('culturePlan.courseTotal') }}：
                            <b
                                style="color:#993300"
                            >{{ c.totalNum }}</b>
                            ，{{ $t('culturePlan.requireNumber') }}：
                            <b
                                style="color:red"
                            >{{ c.planNum }}</b>
                            ，{{ $t('culturePlan.selectedNumber') }}：
                            <b
                                style="color:#009900"
                            >{{ c.actNum }}</b>
                        </div>
                    </div>
                    <div v-if="c.type=='categoryTotalScore'">
                        <div>
                            {{ $t('culturePlan.graduatePlan.courseTip') }}：
                            <b style="color:red">{{ c.planNum }}</b>，
                            {{ $t('culturePlan.graduatePlan.currentSelectedCredits') }}
                            <b
                                style="color:#009900"
                            >{{ c.actNum }}</b>
                        </div>
                    </div>
                </div>

                <div style="float:right">
                    <el-button type="primary" @click="closeRulesDialog">{{ $t("message.confirm") }}</el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog
            :title="$t('culturePlan.cultureSchemePreview')"
            :visible.sync="showCulturePrev"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="50%"
            class="prevDialog"
            append-to-body
        >
            <schemePreview :scheme="scheme" :template-id="cultureId" :data-type="2" />
        </el-dialog>
        <el-dialog
            :title="$t('culturePlan.historyRecord')"
            :visible.sync="showHistoryDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="30%"
            append-to-body
        >
            <div style="min-height:200px">
                <div v-for="(item,index) in history" :key="item.id" style="line-height:25px">
                    <span
                        v-if="item.actionType==1||item.actionType==2"
                    >{{ index+1 }}.{{ item.changeContent }}，{{ item.actionDate }}</span>
                    <span
                        v-if="item.actionType==3"
                        style="color:red"
                    >{{ index+1 }}.{{ item.changeContent }}，{{ item.actionDate }}</span>
                    <span
                        v-if="item.actionType==4"
                        style="color:green"
                    >{{ index+1 }}.{{ item.changeContent }}，{{ item.actionDate }}</span>
                </div>
            </div>
        </el-dialog>
        <courseDetail
            v-if="showCourseDialog"
            :couse-detail="couseDetail"
            :show-course-dialog="showCourseDialog"
            @closeCourseDialog="handlerCloseCourseDialog"
        />
        <ChooseCourseCrossFaulty
            :is-show="showChooseCourseCrossFaultyDialog"
            :student="studentCultureRel"
            :inter-college-courses="interCollegeCourses"
            @reloadPlan="handlerReloadPage"
            @change-visible="showChooseCourseCrossFaultyDialog = false"
        />
    </div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
import { yesOrNo } from 'common/src/filters/commonFilter'
import { getCourseById } from 'common/src/api/resource/course'
import {
    setSmallCourse,
    getSmallCourse,
    getCulturePlanByStudentId,
    getCultureCourseByParam,
    saveCulturePlan,
    updateCulturePlan,
    findStudentCultureRelById,
    updateStudentCultureRelStatus,
    culturePlanActionHistory,
    chooseCourseForCrossFaultyFind,
    deleteTransdisciplinaryCourse,
    ischeckExitRace
} from 'common/src/api/culture/culturePlan'
import scoreStatistics from './scoreStatistics'
import schemePreview from '../culturescheme/schemePreview'
import { build, validate, PLAN_STATUS } from './cultureWorkedPlan'
import { queryDic } from 'common/src/api/dictionary'
import { findFaculty } from 'common/src/api/faculty'
import UTILS from 'common/src/utils/utils'
import ChooseCourseCrossFaulty from './ChooseCourseCrossFaulty'
import courseDetail from 'common/src/views/culture/common/courseDetail'
import { getPower } from 'common/src/api/culture/culturePlan'
export default {
    name: 'GraduatePlan',
    filters: {
        yesOrNo
    },
    components: {
        scoreStatistics,
        schemePreview,
        ChooseCourseCrossFaulty,
        courseDetail
    },
    props: {
        studentCultureRel: {
            default: null // 个人培养计划信息,避免重复查询
        },
        data: {
            default: null // 业务数据，包含培养计划、规则、培养方案数据
        },
        prev: {
            default: false
        },
        isPass: {
            default: 0
        },
        old4m3: {
            default: ''
        },
        trainingCategoryCode: {
            default: ''
        }
    },
    data() {
        return {
            showChooseCourseCrossFaultyDialog: false,
            uid: '',
            rawLabels: null, // 原生课程分类集合
            rawCourses: null, // 原生课程集合
            rawRules: null,
            foreigns: null, // 外国语关系
            courses: [], // 计划列表，(视图绑定的数据)
            interCollegeCourses: [], // 跨院系课程
            tableDynamicColNum: 1, // 动态列数，为课程分类层级最大数
            tableStaticColNum: 11, // 表格静态列数
            totalScore: 0, // 合计学分
            totalTime: 0, // 合计学时
            showAddDialog: false, // 是否显示添加对话框
            showRulesDialog: false, // 是否显示规则对话框
            showCulturePrev: false, // 是否显示预览对话框
            showHistoryDialog: false, // 显示历史记录对话框
            studentId: '',
            templateId: '',
            deleteCourseIds: [], // 删除的课程Id集合
            moveCourseIds: [], //* 移动课程Id集合
            rules: [],
            cultureId: '', // 培养方案id
            scheme: null, // 培养方案对象
            history: [],
            cultureCourseLabelRelationList: [], // 培养计划
            /** 添加课程相关属性**/
            searchCourse: null,
            rawLabelCourse: [], // 添加课程，课程分类下所有课程列表
            filterLabelCourses: [], // 添加课程，过滤后的课程列表
            categoryTotalScore: 0, // 培养方案分类总学分
            startStatus: '', // 判断是否跨院系课程设置
            statusPlan: '',
            labelId: null,
            isEditType: false,
            options: {
                kkxq: [],
                college: [],
                nature: []
            },
            queryForm: {
                nature: '',
                term: '',
                college: '',
                labelId: ''
            },
            showCourseDialog: false,
            couseDetail: {},
            showSelectDialog: false, // 选择课程时是否弹出对话框
            allSmallCourses: [], // 大课对应的所有小课
            selectedSmallCourses: [], // 已选的小课
            smallCoursesParams: [], // 保存已选但未提交的选课参数
            selectedCoursesName: '', // 大课课程名
            selectedCodes: null, // 大课课程代码
            isShowPlan: false,
            coursesData: [],
            role: '',
            projId: ''
        }
    },
    computed: {
        language() {
            return this.$store.getters.language
        },
        ...mapState({
            user: state => state.session.user
        })
    },
    watch: {
        data(newData, oldData) {
            if (newData) {
                this.getCourseInfo()
            }
        },
        deep: true
    },
    mounted() {
        this.studentId = this.$route.query.studentId
        this.init()
        this.getStatus()
        this.getRole()
        //   if (this.studentId) {
        //     this.findStudentCultureRelByIds(this.studentId);
        //   }
        if (this.studentCultureRel) {
            this.statusPlan = this.studentCultureRel.statusPlan
            this.projId = this.studentCultureRel.projId
            this.cultureId = this.studentCultureRel.cultureId
        }
    },
    methods: {
        ...mapActions(['delTab']),
        handlerReloadPage() {
            this.showChooseCourseCrossFaultyDialog = false
            // let res = await findStudentCultureRelById(this.uid);
            // let {code, data: {old4m3}} = res;
            // this.isOld4m3 = old4m3 == 1;
            this.saveCourseHandler(false, () => {
                findStudentCultureRelById(this.uid).then(res => {
                    if (res.code == 200 && res.data) {
                        this.studentCultureRel = res.data
                        this.statusPlan = res.data.statusPlan
                        const isOld4m3 = res.data.old4m3 === 1
                        this.isPass = res.data.statusPlan == 3 ? 1 : 0
                        getCulturePlanByStudentId(this.uid, this.isPass).then(
                            res => {
                                if (res.code == 200) {
                                    this.success = true
                                    this.data = res.data
                                    this.init()
                                }
                            }
                        )
                    }
                })
            })
        },
        getRole() {
            getPower().then(res => {
                this.role = res.data.power
            })
        },
        findStudentCultureRelByIds(id) {
            findStudentCultureRelById(id).then(res => {
                if (res.code == 200 && res.data) {
                    this.statusPlan = res.data.statusPlan
                }
            })
        },
        init() {
            this.coursesData = []
            findFaculty().then(res => {
                const data = {
                    X_YX: res.data
                }
                UTILS.fillSelect(
                    {
                        college: 'X_YX'
                    },
                    data,
                    this.options
                )
            })
            const data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: ['X_KKXQ', 'X_KCXZ']
            }
            queryDic(data).then(res => {
                if (res.code == 200) {
                    UTILS.fillSelect(
                        {
                            kkxq: 'X_KKXQ',
                            nature: 'X_KCXZ'
                        },
                        res.data,
                        this.options
                    )
                    this.getCourseInfo()
                }
            })
        },
        // 获取跨院系课程设置信息
        getStatus() {
            chooseCourseForCrossFaultyFind().then(res => {
                if (res.code == 200) {
                    this.startStatus = res.data.startStatus
                }
            })
        },
        /**
         * @param {selectType} 是否重置selected字段 默认重置
         */
        getCourseInfo(selectType = true) {
            if (this.studentCultureRel) {
                this.uid = this.studentCultureRel.studentId
                if (this.data) {
                    var hasPublicCourse = false
                    this.rawLabels = this.data.coursesLabelList
                    this.data.templateRuleList.forEach(r => {
                        const obj = this.rawLabels.find(
                            label => label.labelId == r.labelId
                        )
                        if (obj) {
                            r.pid = obj.parentId
                            r.name = obj.label
                        } else if (r.labelId == '999999') {
                            hasPublicCourse = true
                            r.pid = '999999'
                            r.name = this.$t('culturePlan.graduatePlan.crossDepartmentalCourses')
                        }
                    })
                    this.rawRules = this.data.templateRuleList.filter(
                        r => r.pid != null
                    )
                    // changeStatus赋值
                    if (this.data.culturePlanList && this.statusPlan == 3) {
                        this.data.culturePlanList.forEach(d => {
                            if (d.changeStatus == 3) {
                                this.data.cultureCourseLabelRelationList.push(
                                    d
                                )
                            } else {
                                this.data.cultureCourseLabelRelationList.forEach(
                                    f => {
                                        if (d.code == f.code) {
                                            f.changeStatus = d.changeStatus
                                        }
                                    }
                                )
                            }
                        })
                    }
                    if (this.data.culturePlanList && this.data.culturePlanList.length > 0) {
                        this.data.culturePlanList.forEach(d => {
                            this.data.cultureCourseLabelRelationList.forEach(
                                f => {
                                    if (d.code == f.code) {
                                        d.period = f.period
                                        d.compulsory = f.compulsory
                                        d.trainingLevelI18n = f.trainingLevelI18n
                                        d.introductionCourse = f.introductionCourse
                                    }
                                }
                            )
                        })
                    }
                    // 移除重复课程分类
                    this.rawLabels = _.uniqWith(this.rawLabels, _.isEqual)
                    this.data.cultureCourseLabelRelationList = _.uniqWith(
                        this.data.cultureCourseLabelRelationList,
                        _.isEqual
                    )
                    this.cultureCourseLabelRelationList = this.data.cultureCourseLabelRelationList
                    const allCourses = this.data.cultureCourseLabelRelationList
                    const list =
                        this.data && this.data.culturePlanList.length > 0
                            ? this.data.culturePlanList
                            : this.data.cultureCourseLabelRelationList
                    const otherFacultyCourse = list.filter(
                        i => i.labelId === 999999
                    )
                    const otherFacultyCourse2 = this.data.culturePlanList.filter(
                        i => i.labelId === 999999
                    )
                    let buildCourses
                    if (this.prev) {
                        // if (this.statusPlan == 3) {
                        //     if (this.old4m3 * 1 == 1) {
                        //         buildCourses = allCourses;
                        //     } else {
                        //         buildCourses = this.data.culturePlanList;
                        //     }
                        // } else {
                        //     buildCourses = allCourses.filter(
                        //         i =>
                        //             list.find(item => item.code === i.code) ||
                        //             !!+i.compulsory
                        //     );
                        // }
                        if (this.data.culturePlanList && this.data.culturePlanList.length > 0) {
                            this.data.culturePlanList.forEach(d => {
                                this.data.cultureCourseLabelRelationList.forEach(e => {
                                    if (d.code == e.code) {
                                        d.remarks = e.remarks
                                    }
                                })
                            })
                        }
                        buildCourses = this.data.culturePlanList
                        this.rawCourses = _.cloneDeep([
                            ...buildCourses,
                            ...otherFacultyCourse2
                        ])
                    } else {
                        if (this.statusPlan == -1) {
                            buildCourses = allCourses.map(i => {
                                i.selected = selectType ? false : i.selected
                                return {
                                    ...i
                                }
                            })
                        } else {
                            buildCourses = allCourses.map(i => {
                                i.selected = selectType
                                    ? !!list.find(e => e.code === i.code)
                                    : i.selected
                                return {
                                    ...i
                                }
                            })
                        }
                        this.rawCourses = _.cloneDeep([
                            ...buildCourses,
                            ...otherFacultyCourse
                        ])
                    }
                    // 移除prev重复课程分类
                    this.rawCourses = _.uniqWith(this.rawCourses, _.isEqual)
                    // 判断数据来源，是培养计划还是培养方案
                    // if (this.prev) {
                    //     let list = [];
                    //     if (this.old4m3 * 1 == 1) {
                    //         list =
                    //             this.data && this.data.culturePlanList.length > 0
                    //                 ? this.data.culturePlanList
                    //                 : this.data.cultureCourseLabelRelationList;
                    //     } else {
                    //         list = this.data && this.data.culturePlanList;
                    //     }
                    //     let allCourses = this.data.cultureCourseLabelRelationList;
                    //     let buildCourses = allCourses.filter(i =>
                    //         list.find(item => item.code === i.code) || i.compulsory
                    //     )
                    //     let otherFacultyCourse = list.filter(i => i.labelId === 999999);
                    //     this.rawCourses = _.cloneDeep([...buildCourses, ...otherFacultyCourse]);
                    // } else {
                    //     let list = [];
                    //     if (this.old4m3 * 1 == 1) {
                    //         list =
                    //             this.data && this.data.culturePlanList.length > 0
                    //                 ? this.data.culturePlanList
                    //                 : this.data.cultureCourseLabelRelationList;
                    //     } else {
                    //         list = this.data && this.data.culturePlanList;
                    //     }
                    //     let otherFacultyCourse = list.filter(i => i.labelId === 999999);
                    //     let allCourses = this.data.cultureCourseLabelRelationList;
                    //     allCourses.forEach(i => i.selected = !!list.find(e => e.code === i.code) || i.compulsory);
                    //     this.rawCourses = _.cloneDeep([...allCourses, ...otherFacultyCourse]);
                    // }

                    // this.rawCourses = _.cloneDeep(
                    //     this.data.cultureCourseLabelRelationList
                    // );
                    // this.rawCourses =
                    //     this.data.culturePlanList &&
                    //     0 < this.data.culturePlanList.length
                    //         ? this.data.culturePlanList
                    //         : _.cloneDeep(
                    //               this.data.cultureCourseLabelRelationList
                    //           );
                    this.rawLabels.push({
                        label: this.$t('culturePlan.graduatePlan.crossDepartmentalCourses'),
                        labelId: '999999',
                        parentId: '0'
                    })
                    this.foreigns = this.data.foreignLanguageList
                    this.categoryTotalScore = this.data.cultureSchemeTotalScoreRule
                    this.buildViewData(
                        this.studentCultureRel.statusPlan == PLAN_STATUS.none &&
                            this.rawCourses.length === 0
                    )
                }
            }
        },
        // 创建视图数据
        buildViewData(isEmpty = false) {
            const obj = build(
                this.rawLabels,
                this.rawCourses,
                !this.prev,
                isEmpty
            )
            // 在职研究生没有跨院系课程
            this.courses = obj.courses.filter(
                i => i.labelId != 999999
            )
            // console.log(this.courses)
            // changeStatus赋值
            // if( this.courses && this.statusPlan != 3){
            //     console.log(this.statusPlan)
            //         this.courses.forEach(d =>{
            //         d.changeStatus = 0
            //     })
            // }
            this.courses.forEach(item => {
                item.isEditType = [1039, 1071, 1550, 1582].includes(
                    item.inntLabelId
                ) // 是否修改课程类型
            })
            // 对比，为了获取添加/删除的课程
            this.initCourses = _.cloneDeep(this.courses)
            // 过滤获取款院系课程(start)
            const coursesArr = []
            this.courses.map(item => {
                if (item.labelId === 999999) {
                    coursesArr.push(item)
                }
                this.isEditType =
                    [47, 558, 1069, 1580].includes(item.labelId) ||
                    [1039, 1071, 1550, 1582].includes(item.labelId) // 是否修改课程类型
            })
            this.interCollegeCourses = coursesArr
            // 过滤获取款院系课程(end)
            this.tableDynamicColNum = obj.tableDynamicColNum
            this.totalScore = obj.totalScore
            this.totalTime = obj.totalTime
            if (this.prev) {
                this.courses.forEach(item => {
                    if (item.changeStatus == 3) {
                        this.totalScore = this.totalScore - item.credits
                        this.totalTime = this.totalTime - item.period
                    }
                })
            }
        },
        resetSelected(c) {
            if (c.selected) {
                const data = {
                    studentId: this.uid,
                    courseCode: c.code,
                    cultureId: this.cultureId,
                    projId: this.projId,
                    labelId: c.labelId
                }
                ischeckExitRace(data).then(res => {
                    if (res.code == 200) {
                        this.totalScore -= +c.credits
                        this.totalTime -= +c.period
                        c.selected = !c.selected
                    }
                })
            } else {
                this.totalScore += +c.credits
                this.totalTime += +c.period
                c.selected = !c.selected
            }
        },
        // 显示删除对话框提示
        showDeleteDialog(course) {
            this.$confirm(
                this.$t('culturePlan.confirmDeleteCourse'),
                this.$t('message.prompt'),
                {
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: 'warning'
                }
            )
                .then(() => {
                    this.confirmDelete(course)
                })
                .catch(e => {})
        },
        getLabelId(course) {
            var electiveCourses = [47, 558, 1069, 1580] // 非学位课
            var proElectiveCourses = [1039, 1071, 1550, 1582] // 专业学位课
            const isElectiveCourses = electiveCourses.includes(course.labelId) // 非学位课
            const isProElectiveCourses = proElectiveCourses.includes(
                course.labelId
            ) // 专业学位课
            if (isElectiveCourses) {
                // 非学位课
                this.courses.forEach(item => {
                    proElectiveCourses.forEach(id => {
                        if (id == item.labelId) {
                            this.labelId = item.labelId
                        }
                    })
                })
            } else if (isProElectiveCourses) {
                this.courses.forEach(item => {
                    electiveCourses.forEach(id => {
                        if (id == item.labelId) {
                            this.labelId = item.labelId
                        }
                    })
                })
            }
        },
        // 修改课程类型
        /**
         * @param {course} 操作项的所有数据
         * @param {status} 方案状态
         */
        removeCourse(course, status) {
            if (course.courseGroupId) {
                this.$message({
                    type: 'warning',
                    message: '已分组的课程不能进行课程类别修改'
                })
                return
            } else {
                this.getLabelId(course)
                this.copyCurrentCourseLableId = !this.copyCurrentCourseLableId
                    ? _.cloneDeep(course.labelId)
                    : this.copyCurrentCourseLableId // 当前操作数据暂存lableId （学位课与非学位课）
                this.copyRelativeCourseLableId = !this.copyRelativeCourseLableId
                    ? _.cloneDeep(this.labelId)
                    : this.copyRelativeCourseLableId // 当前操作数据相对的暂存labelId（学位课与非学位课）
                const array = this.data.cultureCourseLabelRelationList
                    ? this.data.cultureCourseLabelRelationList
                    : []

                // console.log(this.copyCurrentCourseLableId)
                // console.log(this.copyRelativeCourseLableId)
                // console.log(course)
                // console.log(array)
                array.forEach(e => {
                    if (e.id == course.id) {
                        // console.log(e.id)
                        e.labelId =
                            this.labelId == this.copyCurrentCourseLableId
                                ? this.copyCurrentCourseLableId
                                : this.copyRelativeCourseLableId
                    }
                    const index = this.courses.findIndex(c => c.id == e.id)
                    if (index > -1) {
                        e.isEditType = this.courses[index].isEditType
                        e.selected = this.courses[index].selected
                    }
                })
                this.data.cultureCourseLabelRelationList = array
                this.getCourseInfo(false)
                this.coursesData.push({
                    operation: '4',
                    courseLabelRelationId: course.id,
                    courseCode: course.code ? course.code : null,
                    courseId: course.courseId,
                    labelId: this.labelId
                })
                const filterList = this.coursesData.filter(
                    e => e.courseLabelRelationId == course.id
                )
                if (filterList.length > 1) {
                    this.coursesData = this.coursesData.filter(e => {
                        return e.courseLabelRelationId !== course.id
                    })
                }
            }
        },
        showAppendDialog(course) {
            this.queryForm.labelId = course.label.labelId
            const studentId = this.uid
            this.searchCourse = ''
            this.rawLabelCourse = []
            this.filterLabelCourses = []
            // 绑定该分类下已经存在的课程
            const selectedCourses = this.courses.filter(
                c => c.labelId == this.queryForm.labelId
            )
            let templateId = ''
            if (this.user.currentManageDptId == 2) {
                templateId = this.$route.query.templateId
            }
            // 查询所有分类下的课程
            getCultureCourseByParam(
                studentId,
                this.queryForm.labelId,
                '',
                '',
                '',
                '',
                '',
                '',
                templateId
            ).then(res => {
                if (res.code == 200) {
                    res.data.forEach(c => {
                        if (selectedCourses.some(c_ => c_.code == c.code)) {
                            c.disabled = true
                            c.checked = true
                        } else {
                            c.checked = false
                        }
                    })
                    this.rawLabelCourse = res.data
                    this.filterLabelCourses = _.cloneDeep(
                        this.calculateRowSpan(res.data)
                    )
                }
            })
            this.resetAddCourse()
            this.showAddDialog = true
        },
        // 添加培养计划
        async addCulturePlanHandle(status) {
            const labelIds = []

            const data = []
            this.courses
                .filter(i => i.selected)
                .forEach(c => {
                    if (c.type == 'row' && labelIds.indexOf(c.labelId) == -1) {
                        labelIds.push(c.labelId)
                    }
                })
            const courses = this.courses.filter(i => i.id)
            const smallCourses = this.courses.filter(i => !i.id)
            labelIds.forEach(id => {
                const courses1 = courses
                    .filter(
                        c => c.type == 'row' && c.labelId == id && c.selected
                    )
                    .map(c => c.id)
                const smallCourses1 = smallCourses
                    .filter(
                        c => c.type == 'row' && c.labelId == id && c.selected
                    )
                    .map(c => c.code)
                const obj = {
                    labelId: id,
                    coursesRelId: courses1
                }
                if (smallCourses1.length > 0) {
                    obj.courseCodes = smallCourses1
                }
                data.push(obj)
            })
            //  console.log(data)
            // if (data.length == 0) {
            //     this.$message({
            //         type: "error",
            //         message: "没有添加课程，请先添加课程。"
            //     });
            //     return;
            // }
            return await saveCulturePlan(
                data,
                this.uid,
                status,
                this.studentCultureRel.teacherId || 'null'
            )
            // saveCulturePlan(
            //     data,
            //     this.uid,
            //     status,
            //     this.studentCultureRel.teacherId || 'null'
            // ).then(res => {
            //     if (res.code == 200) {
            //         this.$message({
            //             type: "success",
            //             message: msg
            //         });
            //         falgBack && this.back();
            //     }
            // });
        },
        // 更新培养计划
        async updateCulturePlanHandle(status, msg, falgBack = true) {
            // 判断有没有课程

            // let labelIds = [];
            // this.courses.forEach(c => {
            //     if (c.type == "row" && labelIds.indexOf(c.labelId) == -1) {
            //         labelIds.push(c.labelId);
            //     }
            // });
            // let data1 = [];
            // labelIds.forEach(id => {
            //     let courses = this.courses
            //         .filter(c => c.type == "row" && c.labelId == id)
            //         .map(c => c.id);
            //     data1.push({ labelId: id, coursesRelId: courses });
            // });
            // if (data1.length == 0) {
            //     this.$message({
            //         type: "error",
            //         message: "没有添加课程，请先添加课程。"
            //     });
            //     return;
            // }

            // let data = [];
            let data = this.initCourses.reduce((p, c) => {
                const course = this.courses.find(e => {
                    if (c.id) {
                        return e.id === c.id
                    }
                    return e.code === c.code
                })
                if (course.selected != c.selected) {
                    if (course.selected) {
                        // 添加行
                        p.push({
                            operation: '1',
                            courseLabelRelationId: c.courseLabelRelationId,
                            code: c.code,
                            labelId: c.labelId
                        })
                    } else {
                        // 删除行
                        const oldCourse = this.data.culturePlanList.find(
                            e => e.code === course.code
                        )
                        p.push({
                            operation: '2',
                            // courseCode: c.code,
                            id: oldCourse ? oldCourse.id : c.id
                        })
                    }
                }
                return p
            }, [])
            // 删除跨院系课程
            const otherFacultyCourses = _.cloneDeep(
                this.courses.filter(i => i.labelId === 999999)
            )
            const deletedOtherFacultyCourses = this.data.culturePlanList.filter(
                i =>
                    i.labelId === 999999 &&
                    !otherFacultyCourses.find(e => e.id === i.id)
            )
            deletedOtherFacultyCourses.forEach(i => {
                data.push({
                    operation: '2',
                    // courseCode: c.code,
                    id: i.id
                })
            })
            // 添加行
            // this.courses.forEach(c => {
            //     if (c.command == "addRow") {
            //         data.push({
            //             operation: "1",
            //             courseLabelRelationId: c.id
            //         });
            //     }
            // });
            // 删除行
            // this.deleteCourseIds &&
            //     this.deleteCourseIds instanceof Array &&
            //     this.deleteCourseIds.forEach(c => {
            //         data.push({
            //             operation: "2",
            //             courseCode: c.code,
            //             id: c.id
            //         });
            //     });
            //* 移动课程
            // this.moveCourseIds &&
            //     this.moveCourseIds instanceof Array &&
            //     _.each(this.moveCourseIds, c => {
            //         data.push({
            //             operation: "4",
            //             id: c.id,
            //             courseId: c.courseId,
            //             courseCode: c.courseCode,
            //             labelId: c.labelId
            //         });
            //     });
            if (data.length === 0) {
                if (
                    this.old4m3 == '1' &&
                    this.data.culturePlanList.length === 0
                ) {
                    data = this.courses
                        .filter(i => i.id && i.selected)
                        .map(c => ({
                            operation: '1',
                            courseLabelRelationId: c.id
                        }))
                }
            }
            if (this.coursesData.length > 0) {
                this.coursesData.forEach(d => {
                    data.push(d)
                })
            }
            return await updateCulturePlan(
                data,
                this.uid,
                status,
                this.studentCultureRel.teacherId || 'null'
            )
            // if (data.length > 0) {
            //     return await updateCulturePlan()
            //     updateCulturePlan(
            //         data,
            //         this.uid,
            //         status,

            //     ).then(res => {
            //         if (res.code == 200) {
            //             this.$message({
            //                 type: "success",
            //                 message: msg
            //             });
            //             falgBack && this.back();
            //         }
            //     });
            // } else {
            //     if (this.old4m3 == "1" && this.data.culturePlanList.length ===  0) {
            //             let data = this.courses.filter(i => i.id && i.selected).map(c => ({operation: "1",courseLabelRelationId: c.id}))
            //             return await updateCulturePlan(data, this.uid, status, this.studentCultureRel.teacherId || 'null');
            //             updateCulturePlan(
            //                 data,
            //                 this.uid,
            //                 status,
            //                 this.studentCultureRel.teacherId || 'null'
            //             ).then(res => {
            //                 if (res.code == 200) {
            //                     this.$message({
            //                         type: "success",
            //                         message: msg
            //                     });

            //                 }
            //             }).finally( _ => {
            //                 falgBack && this.back();
            //             });
            //     } else {
            //         return await updateCulturePlan([], this.uid, status, this.studentCultureRel.teacherId || 'null');
            //         updateCulturePlan(
            //             [],
            //             this.uid,
            //             status,
            //             this.studentCultureRel.teacherId || 'null'
            //         ).then(res => {
            //             if (res.code == 200) {
            //                 this.$message({
            //                     type: "success",
            //                     message: msg
            //                 });

            //             }
            //         }).finally( _ => {
            //             falgBack && this.back();
            //         });
            //     }

            // }
        },
        // 保存
        async saveCourseHandler(falgBack, callback) {
            if (this.studentCultureRel.statusPlan == PLAN_STATUS.none) {
                this.addCulturePlanHandle(PLAN_STATUS.draft)
                    .then(res => {
                        if (res.code == 200) {
                            this.$message({
                                type: 'success',
                                message: this.$t('culturePlan.success')
                            })
                            callback && callback()
                            if (this.coursesData.length > 0) {
                                this.updateCulturePlanHandle(PLAN_STATUS.draft)
                            }
                            falgBack && this.back()
                        }
                    })
                // .finally(_ => {
                //     falgBack && this.back();
                // });
            } else {
                const result = this.updateCulturePlanHandle(PLAN_STATUS.draft)
                result
                    .then(res => {
                        if (res.code == 200) {
                            this.$message({
                                type: 'success',
                                message: this.$t('culturePlan.success')
                            })
                            callback && callback()
                            falgBack && this.back()
                        }
                    })
                // .finally(_ => {
                //     falgBack && this.back();
                // });
            }
        },
        saveCourse(falgBack = true) {
            if (this.role == 4) {
                this.$confirm(
                    this.$t('culturePlan.confirmSavePlan') + '<br/>',
                    this.$t('message.prompt'),
                    {
                        confirmButtonText: this.$t('message.confirm'),
                        cancelButtonText: this.$t('message.cancel'),
                        type: 'warning',
                        dangerouslyUseHTMLString: true
                    }
                ).then(() => {
                    // if(this.coursesData.length > 0){
                    //     this.uid = this.studentCultureRel.studentId;
                    //     updateCulturePlan(this.coursesData, this.uid, this.statusPlan, 'null').then((res)=>{
                    //         if (res.code == 200) {
                    //             this.saveCourseHandler(falgBack);
                    //         }
                    //     })
                    // }
                    this.saveCourseHandler(falgBack)
                })
            } else {
                let flag = true
                const result = validate(
                    this.rawLabels,
                    this.courses.filter(i => i.selected),
                    this.rawRules,
                    this.foreigns,
                    this.cultureCourseLabelRelationList,
                    this.categoryTotalScore
                )
                if (!result.success) {
                    this.showRulesDialog = true
                    this.rules = result.errors
                    return
                }
                this.courses.forEach(d => {
                    if (d.selected == false && d.compulsory == 1) {
                        flag = false
                        return
                    }
                })
                if (!flag) {
                    this.$confirm(this.$t('culturePlan.graduatePlan.selectCourseSave'), {
                        confirmButtonText: this.$t('message.confirm'),
                        cancelButtonText: this.$t('message.cancel'),
                        type: 'warning',
                        dangerouslyUseHTMLString: true
                    })
                } else {
                    this.$confirm(
                        this.$t('culturePlan.confirmSavePlan') + '<br/>',
                        this.$t('message.prompt'),
                        {
                            confirmButtonText: this.$t('message.confirm'),
                            cancelButtonText: this.$t('message.cancel'),
                            type: 'warning',
                            dangerouslyUseHTMLString: true
                        }
                    ).then(() => {
                        // if(this.coursesData.length > 0){
                        //     this.uid = this.studentCultureRel.studentId;
                        //     updateCulturePlan(this.coursesData, this.uid, this.statusPlan, 'null').then((res)=>{
                        //         if (res.code == 200) {
                        //             this.saveCourseHandler(falgBack);
                        //         }
                        //     })
                        // }
                        if (this.smallCoursesParams.length > 0) {
                            this.setSmallCourses(falgBack)
                        } else {
                            this.saveCourseHandler(falgBack)
                        }
                    })
                }
            }
        },
        // 提交
        submitCourse() {
            // if (!this.studentCultureRel.teacherId) {
            //     this.$message({
            //         type: "warning",
            //         message: "没有导师无法提交个人计划"
            //     });
            //     return;
            // }
            if (this.role == 4) {
                this.$confirm(
                    this.$t('culturePlan.confirmSubmitPlan') +
                        "<br/><span style='color:red'>*" +
                        this.$t('culturePlan.checkNoCancel') +
                        '</span>',
                    this.$t('message.prompt'),
                    {
                        confirmButtonText: this.$t('message.confirm'),
                        cancelButtonText: this.$t('message.cancel'),
                        type: 'warning',
                        dangerouslyUseHTMLString: true
                    }
                ).then(() => {
                    if (
                        this.studentCultureRel.statusPlan ==
                        PLAN_STATUS.none
                    ) {
                        this.addCulturePlanHandle(
                            PLAN_STATUS.checking,
                            this.$t('culturePlan.success')
                        )
                            .then(res => {
                                if (res.code == 200) {
                                    this.$message({
                                        type: 'success',
                                        message: this.$t(
                                            'culturePlan.success'
                                        )
                                    })
                                    this.back()
                                }
                            })
                        // .finally(_ => {
                        //     this.back();
                        // });
                    } else {
                        const result = this.updateCulturePlanHandle(
                            PLAN_STATUS.checking
                        )
                        result
                            .then(res => {
                                if (res.code == 200) {
                                    this.$message({
                                        type: 'success',
                                        message: this.$t(
                                            'culturePlan.success'
                                        )
                                    })
                                    this.back()
                                }
                            })
                        // .finally(_ => {
                        //     this.back();
                        // });
                        // this.updateCulturePlanHandle(
                        //     PLAN_STATUS.checking,

                        // );
                    }
                })
            } else {
                let flag = true
                const result = validate(
                    this.rawLabels,
                    this.courses.filter(i => i.selected),
                    this.rawRules,
                    this.foreigns,
                    this.cultureCourseLabelRelationList,
                    this.categoryTotalScore
                )
                if (!result.success) {
                    this.showRulesDialog = true
                    this.rules = result.errors
                    return
                }
                this.courses.forEach(d => {
                    if (d.selected == false && d.compulsory == 1) {
                        flag = false
                        return
                    }
                })
                if (!flag) {
                    this.$confirm(this.$t('culturePlan.undergraduatePlan.addRequiredCourse'), {
                        confirmButtonText: this.$t('message.confirm'),
                        cancelButtonText: this.$t('message.cancel'),
                        type: 'warning',
                        dangerouslyUseHTMLString: true
                    })
                } else {
                    this.$confirm(
                        this.$t('culturePlan.confirmSubmitPlan') +
                            "<br/><span style='color:red'>*" +
                            this.$t('culturePlan.checkNoCancel') +
                            '</span>',
                        this.$t('message.prompt'),
                        {
                            confirmButtonText: this.$t('message.confirm'),
                            cancelButtonText: this.$t('message.cancel'),
                            type: 'warning',
                            dangerouslyUseHTMLString: true
                        }
                    ).then(() => {
                        if (this.smallCoursesParams.length > 0) {
                            setSmallCourse(this.smallCoursesParams)
                                .then(res => {
                                    if (res.code == 200) {
                                        if (
                                            this.studentCultureRel.statusPlan ==
                                            PLAN_STATUS.none
                                        ) {
                                            this.addCulturePlanHandle(
                                                PLAN_STATUS.checking,
                                                this.$t('culturePlan.success')
                                            )
                                                .then(res => {
                                                    if (res.code == 200) {
                                                        this.$message({
                                                            type: 'success',
                                                            message: this.$t(
                                                                'culturePlan.success'
                                                            )
                                                        })
                                                        this.back()
                                                    }
                                                })
                                            // .finally(_ => {
                                            //     this.back();
                                            // });
                                        } else {
                                            const result = this.updateCulturePlanHandle(
                                                PLAN_STATUS.checking
                                            )
                                            result
                                                .then(res => {
                                                    if (res.code == 200) {
                                                        this.$message({
                                                            type: 'success',
                                                            message: this.$t(
                                                                'culturePlan.success'
                                                            )
                                                        })
                                                        this.back()
                                                    }
                                                })
                                            // .finally(_ => {
                                            //     this.back();
                                            // });
                                            // this.updateCulturePlanHandle(
                                            //     PLAN_STATUS.checking,

                                            // );
                                        }
                                    }
                                })
                                .catch(e => {
                                    this.$message({
                                        type: 'error',
                                        message: this.$t('culturePlan.undergraduatePlan.courseSelectionFailed')
                                    })
                                })
                        } else {
                            if (
                                this.studentCultureRel.statusPlan ==
                                PLAN_STATUS.none
                            ) {
                                this.addCulturePlanHandle(
                                    PLAN_STATUS.checking,
                                    this.$t('culturePlan.success')
                                )
                                    .then(res => {
                                        if (res.code == 200) {
                                            this.$message({
                                                type: 'success',
                                                message: this.$t(
                                                    'culturePlan.success'
                                                )
                                            })
                                            this.back()
                                        }
                                    })
                                // .finally(_ => {
                                //     this.back();
                                // });
                            } else {
                                const result = this.updateCulturePlanHandle(
                                    PLAN_STATUS.checking
                                )
                                result
                                    .then(res => {
                                        if (res.code == 200) {
                                            this.$message({
                                                type: 'success',
                                                message: this.$t(
                                                    'culturePlan.success'
                                                )
                                            })
                                            this.back()
                                        }
                                    })
                                // .finally(_ => {
                                //     this.back();
                                // });
                                // this.updateCulturePlanHandle(
                                //     PLAN_STATUS.checking,

                                // );
                            }
                        }
                    })
                }
            }
        },
        // 返回
        back() {
            this.isShowPlan = true
            this.$emit('showPlan', this.isShowPlan)
        },

        // 重置添加课程
        // resetAddCourse() {
        //     this.queryForm.nature = "";
        //     this.queryForm.college = "";
        //     this.queryForm.term = "";
        //     this.searchCourse = "";
        // },
        // 筛选添加课程
        // filterAddCourse() {
        //     let selectedCourses = this.courses.filter(
        //         c => c.labelId == this.queryForm.labelId
        //     );
        //     //查询所有分类下的课程
        //     getCultureCourseByParam(
        //         this.uid,
        //         this.queryForm.labelId,
        //         this.queryForm.nature,
        //         this.queryForm.college,
        //         this.queryForm.term
        //     ).then(res => {
        //         if (res.code == 200) {
        //             res.data.forEach(c => {
        //                 if (selectedCourses.some(c_ => c_.code == c.code)) {
        //                     c.disabled = true;
        //                     c.checked = true;
        //                 } else {
        //                     c.checked = false;
        //                 }
        //             });
        //             this.rawLabelCourse = res.data;
        //             this.filterLabelCourses = _.cloneDeep(
        //                 this.calculateRowSpan(res.data)
        //             );
        //         }
        //     });
        // },
        // 保存课程添加
        // addCourseSave() {
        //     if (!this.showAddDialog) {
        //         return;
        //     }
        //     this.showAddDialog = false;
        //     let customed =
        //         this.studentCultureRel.statusPlan != 1 ? true : false;
        //     //获取可选且选中的复选框的课程
        //     let courses = this.filterLabelCourses.filter(
        //         c => !c.disabled && c.checked
        //     );
        //     if (courses.length > 0) {
        //         courses.forEach(c => {
        //             let isOldCourse = false;
        //             if (
        //                 customed &&
        //                 this.deleteCourseIds
        //                     .map(c_ => c_.courseLabelRelationId)
        //                     .includes(c.id)
        //             ) {
        //                 _.remove(
        //                     this.deleteCourseIds,
        //                     c_ => c_.courseLabelRelationId == c.id
        //                 );
        //                 isOldCourse = true;
        //             }
        //             let addRow = {
        //                 id: c.id,
        //                 code: c.code,
        //                 name: c.coursesName,
        //                 nameEn: c.coursesNameEn,
        //                 credits: c.credits,
        //                 period: c.period, //未确定的字段
        //                 term: c.term, //未确定的字段
        //                 labelId: c.labelId,
        //                 isElective: c.isElective,
        //                 courseGroupId: c.courseGroupId,
        //                 parentId: c.parentId,
        //                 groupRemark: c.groupRemark, //未统一
        //                 parentRemark: c.parentRemark,
        //                 chooseNum: c.chooseNum,
        //                 totalNum: c.totalNum,
        //                 parentChooseNum: c.parentChooseNum,
        //                 parentTotalNum: c.parentTotalNum,
        //                 collegeI18n: c.collegeI18n,
        //                 remark: c.remarks //无数据
        //             };
        //             if (customed && !isOldCourse) {
        //                 addRow.command = "addRow";
        //             }
        //             this.rawCourses.push(addRow);
        //         });
        //         this.buildViewData();
        //     }
        // },
        /**
         * 删除课程
         */
        confirmDelete(course) {
            const data = [
                {
                    id: course.id
                    // operation: 2
                }
            ]
            deleteTransdisciplinaryCourse(data).then(res => {
                if (res.code == 200) {
                    findStudentCultureRelById(this.uid).then(res => {
                        if (res.code == 200 && res.data) {
                            this.studentCultureRel = res.data
                            this.statusPlan = res.data.statusPlan
                            const isOld4m3 = res.data.old4m3 === 1
                            this.isPass = res.data.statusPlan == 3 ? 1 : 0
                            getCulturePlanByStudentId(this.uid, this.isPass).then(
                                res => {
                                    if (res.code == 200) {
                                        this.success = true
                                        this.data = res.data
                                        this.init()
                                    }
                                }
                            )
                        }
                    })
                }
            })
            // updateCulturePlan(
            //     data,
            //     this.uid,
            //     PLAN_STATUS.draft,
            //     this.studentCultureRel.teacherId || "null"
            // ).finally(() => {
            //     let result = this.updateCulturePlanHandle(
            //         PLAN_STATUS.draft,
            //         "",
            //         false
            //     );
            //     result.finally(_ => {
            //         findStudentCultureRelById(this.uid).then(res => {
            //             if (res.code == 200 && res.data) {
            //                 this.studentCultureRel = res.data;
            //                 let isOld4m3 = res.data.old4m3 === 1;
            //                 getCulturePlanByStudentId(
            //                     this.uid,
            //                     this.isPass
            //                 ).then(res => {
            //                     if (res.code == 200) {
            //                         this.success = true;
            //                         this.data = res.data;
            //                         this.init();
            //                     }
            //                 });
            //             }
            //         });
            //     });
            // this.rawCourses.forEach(i => {
            //     let course = this.courses.find(e => e.id === i.id);
            //     if (course) {
            //         i.selected = course.selected;
            //     }
            // })
            // this.buildViewData();
            // });
            // if (this.studentCultureRel.statusPlan != 1 && !course.command) {
            //     this.deleteCourseIds.push({
            //         id: course.id,
            //         courseLabelRelationId: course.courseLabelRelationId
            //     }); //仅保存旧课程Id，command==addRow为新课程
            //     course = null;
            // }
        },

        // moveCourse(course) {
        //     if (this.__checkMoveAvaliable(course)) {
        //         if (this.__mDelete(course) && this.__mAdd(course)) {
        //             this.moveCourseIds.push({
        //                 id: course.id,
        //                 courseId: course.courseId,
        //                 code: course.code,
        //                 courseCode: course.courseCode,
        //                 labelId: course.labelId
        //             });
        //             this.buildViewData();
        //         }
        //     }
        // },

        // __checkMoveAvaliable(course) {
        //     if ("1" !== course.creditLimit) {
        //         return true;
        //     }
        //     let currentLabelCourses = _.filter(this.rawCourses, c => {
        //         return (
        //             c.labelId === course.labelId && c.isScorePass && c.selCourse
        //         );
        //     });
        //     let currentLabelCoursesCreditTotal = _.reduce(
        //         currentLabelCourses,
        //         (sum, c) => sum + parseFloat(c.credits),
        //         0
        //     );
        //     let remainCredit =
        //         currentLabelCoursesCreditTotal - parseFloat(course.credits);
        //     if (remainCredit - parseFloat(course.label.credit) >= 0) {
        //         return true;
        //     } else {
        //         this.$message({
        //             type: "error",
        //             message:
        //                 "课程移动后，所在类别剩余课程总学分小于类别要求学分，因此无法移动。"
        //         });
        //     }
        // },

        // __mDelete(course) {
        //     return _.remove(this.rawCourses, c => c.id == course.id);
        // },
        // __mAdd(course) {
        //     let type3Label = _.find(
        //         this.rawLabels,
        //         label => "3" === label.labelType
        //     );
        //     if (type3Label) {
        //         course.labelId = type3Label.labelId;
        //         course.label = type3Label;
        //         let result = this.rawCourses.push(course);
        //         return result;
        //     }
        // },

        // 取消课程添加
        cancelCourseSave() {
            this.showAddDialog = false
        },
        // 取消规则对话框
        closeRulesDialog() {
            this.showRulesDialog = false
        },
        // 获取季度文本值
        getQuarter(semesters) {
            if (semesters) {
                const quarters = semesters
                    .split(',')
                    .map(v => {
                        if (v == 1) {
                            return this.$t('culturePlan.spring')
                        } else if (v == 2) {
                            return this.$t('culturePlan.autumn')
                        } else if (v == 3) {
                            return this.$t('culturePlan.springautumn')
                        } else {
                            return null
                        }
                    })
                    .filter(s => s != null)
                return quarters.length > 0 ? quarters.join(',') : ''
            } else {
                return ''
            }
        },
        // searchAddCourse() {
        //     let courses = this.rawLabelCourse.filter(c => {
        //         return (
        //             c.code.indexOf(this.searchCourse) > -1 ||
        //             (c.coursesName &&
        //                 c.coursesName.indexOf(this.searchCourse) > -1) ||
        //             (c.coursesNameEn &&
        //                 c.coursesNameEn.indexOf(this.searchCourse) > -1)
        //         );
        //     });
        //     this.filterLabelCourses = this.calculateRowSpan(
        //         _.cloneDeep(courses)
        //     );
        // },
        // clearAddCourse() {
        //     this.filterLabelCourses.forEach(c => {
        //         if (!c.disabled) {
        //             c.checked = false;
        //         }
        //     });
        // },
        calculateRowSpan(courses) {
            const groupIds = []
            courses.forEach(c => {
                if (c.courseGroupId && !groupIds.includes(c.courseGroupId)) {
                    groupIds.push(c.courseGroupId)
                }
            })
            const handleIds = []
            groupIds.forEach(groupId => {
                courses.forEach(c => {
                    if (
                        c.courseGroupId == groupId &&
                        !handleIds.includes(c.courseGroupId)
                    ) {
                        handleIds.push(c.courseGroupId)
                        c.rowspan = courses.filter(
                            c_ => c_.courseGroupId == groupId
                        ).length
                    }
                })
            })
            return courses
        },
        getTermText(val) {
            const option = this.options.kkxq.find(obj => obj.value == val)
            if (option) {
                return option.label
            } else {
                return ''
            }
        },
        getIsElectiveText(val) {
            if (val >= 0) {
                return val == 1 ? this.$t('culturePlan.graduatePlan.textFalse') : this.$t('culturePlan.graduatePlan.textTrue')
            } else {
                return ''
            }
        },
        showCourseDetail(c) {
            this.couseDetail = c
            this.showCourseDialog = true
        },
        handlerCloseCourseDialog() {
            this.showCourseDialog = false
        },
        handleSelectionChange(val) {
            this.selectedSmallCourses = val
        },
        // 获取大课对应的小课
        getSmallCourses(c) {
            if (c.chosen == 1) {
                if (this.smallCoursesParams.length > 0) {
                    this.smallCoursesParams = this.smallCoursesParams.filter(
                        d => d.complationsId != c.code
                    )
                    this.courses.forEach(d => {
                        if (d.code == c.code) {
                            d.chosen = 0
                            d.selected = false
                        }
                    })
                } else {
                    c.chosen = 0
                    c.selected = false
                }
            } else {
                this.showSelectDialog = true
                var paras = {
                    studentId: this.uid,
                    complationsId: c.code
                }
                getSmallCourse(paras).then(res => {
                    this.allSmallCourses = res.data
                    //  this.$nextTick(()=>{
                    //     this.allSmallCourses.forEach((row,index)=>{
                    //         if(row.chosen*1==1){
                    //             this.$refs.multipleTable.toggleRowSelection(row,true);
                    //             }
                    //         })
                    //  })
                })
            }
            this.selectedCodes = c.code
            this.selectedCoursesName = c.name
        },
        // 获取多次选课的参数
        getCoursesParams() {
            const courseCodes = this.selectedSmallCourses.map(
                ele => ele.courseCode
            )
            const params = {
                studentId: this.uid,
                complationsId: this.selectedCodes,
                courseCodeList: courseCodes || []
            }
            if (courseCodes && courseCodes.length > 0) {
                this.courses.forEach(d => {
                    if (d.code == this.selectedCodes) {
                        d.chosen = 1
                        d.selected = true
                    }
                })
            } else {
                this.courses.forEach(d => {
                    if (d.code == this.selectedCodes) {
                        d.chosen = 0
                        d.selected = false
                    }
                })
            }
            this.smallCoursesParams.push(params)
            this.showSelectDialog = false
        },
        // 选课
        setSmallCourses(falgBack) {
            setSmallCourse(this.smallCoursesParams)
                .then(res => {
                    if (res.code == 200) {
                        // this.$message({
                        //     type: "success",
                        //     message: "选择课程成功"
                        // });
                        this.saveCourseHandler(falgBack)
                        // this.handlerReloadPage()
                    }
                })
                .catch(e => {
                    this.$message({
                        type: 'error',
                        message: this.$t('culturePlan.undergraduatePlan.courseSelectionFailed')
                    })
                })
        },
        cancelSmallCourses() {
            this.showSelectDialog = false
        }
    }
}
</script>
<style lang="scss" scoped>
.selected-course {
    color: red;
}

.selected-disabled {
    color: #909399;
}
.remove-gray{
    color:#aaa
}

.base-title {
    border-bottom: 1px solid #cccccc;
    line-height: 30px;
    margin-bottom: 20px;
}

.base-sub-title {
    text-align: center;
    font-size: 20px;
    padding-bottom: 20px;
}

.personal {
    width: 100%;
    text-align: center;
    border-collapse: collapse;
    border: 1px solid #000000;
    font-size: 12px !important;
    td,
    th {
        text-align: center;
        line-height: 30px;
        border-collapse: collapse;
        border: 1px solid #a5a5a5;
        background: #fff;
        color: #606266;
    }
}

.nowrap {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

.one-btn {
    width: 60px;
}

.two-btn {
    width: 130px;
}

.tooltip {
    display: block;
    width: 100%;
    height: 100%;
}
</style>
